import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Router, ActivatedRoute } from '@angular/router';
import { DatePipe } from '@angular/common';
import { CommonService } from '../../../../services-common/common.service';
import { StorageCommonService } from '../../xstorage-manage-services/storage-common.service';
import { StoragePurchaseManageService } from '../../xstorage-manage-services/storage-purchase-manage.service';
import { StorageWarehousOrderService } from '../../xstorage-manage-services/storage-warehous-order.service';

@Component({
  selector: 'app-storage-warehous-editcg',
  templateUrl: './storage-warehous-editcg.component.html',
  styleUrls: ['./storage-warehous-editcg.component.scss'],
  providers: [DatePipe]
})
export class StorageWarehousEditcgComponent implements OnInit {

  routeParams: any = {};
  detailsData: any = {}; // 编辑详情

  flexLabelWidth: string = '108px';
  formParams: any = {
    purchaseNumber: '', // 采购单号
    supId: '', // 供应商
    whPutId: '', // 入库仓库
    quality: '', // 入库品质
    arrivalTime: '', // 预计到货日期
    contractEnclosure: '', // 附件
    remark: '' // 备注
  };
  
  supplierName: string = ''; // 供应商name
  supplierOptions: any[] = []; // 供应商Options
  purchaseOptions: any[] = []; // 采购单Options
  warehouseOptions: any[] = []; // 仓库Options

  detailedTableData: Array<any> = [];

  submitLoading = false;

  /**
   * 选择商品
   * ----------------------------------------------------------------
   */
  isGoodVisible = false;
  goodTableParams: any = {
    loading: false,
    tableData: []
  };

  /**
   * ----------------------------------------------------------------
   * Table Check
   * ----------------------------------------------------------------
   */
  checked = false;
  indeterminate = false;
  listOfCurrentPageData: readonly any[] = [];
  setOfCheckedId = new Set<number>();
  setOfCheckedArr: Array<any> = [];

  updateCheckedSet(id: number, checked: boolean): void {
    if (checked) {
      let checkedItem = this.listOfCurrentPageData.find(item => item.whGoodsId === id);
      let setIds = this.setOfCheckedArr.map(m => m.whGoodsId);
      this.setOfCheckedId.add(id);

      if (!setIds.includes(id)) {
        let tmpNum = (checkedItem.purchaseNumber || 0) - (checkedItem.frozenNumber || 0) - (checkedItem.stockNumber || 0);
        this.setOfCheckedArr.push({
          ...checkedItem,
          planDetailsId: checkedItem.id,
          type: checkedItem.snState === 0 ? 1 : 3, // 1：管控 3：普通
          number: !this.commonService.isEmpty(tmpNum) ? tmpNum : '', // 植入最大数量(采购数 - 冻结数 - 已入库数)
          price: checkedItem.purchasePrice || '' // 单价
        });
      }
    } else {
      let delCheckedIndex = this.setOfCheckedArr.findIndex(item => item.whGoodsId === id);
      this.setOfCheckedId.delete(id);

      this.setOfCheckedArr.splice(delCheckedIndex, 1);
    }
  }

  onItemChecked(id: number, checked: boolean): void {
    this.updateCheckedSet(id, checked);
    this.refreshCheckedStatus();
  }

  onAllChecked(value: boolean): void {
    // (行状态正常lineState === 0 | 采购数量 - 冻结数 - 已入库数量 != 0) 可选
    const listOfCurrentPageData = this.listOfCurrentPageData.filter(item => {
      let tmpNum = (item.purchaseNumber || 0) - (item.frozenNumber || 0) - (item.stockNumber || 0);
      return item.lineState === 0 && tmpNum !== 0;
    });
    // const listOfCurrentPageData = this.listOfCurrentPageData.filter(item => item.lineState === 0);
    listOfCurrentPageData.forEach(item => this.updateCheckedSet(item.whGoodsId, value));
    this.refreshCheckedStatus();
  }

  onCurrentPageDataChange($event: readonly any[]): void {
    this.listOfCurrentPageData = $event;
    this.refreshCheckedStatus();
  }

  refreshCheckedStatus(): void {
    // (行状态正常lineState === 0 | 采购数量 - 冻结数 - 已入库数量 != 0) 可选
    const listOfCurrentPageData = this.listOfCurrentPageData.filter(item => {
      let tmpNum = (item.purchaseNumber || 0) - (item.frozenNumber || 0) - (item.stockNumber || 0);
      return item.lineState === 0 && tmpNum !== 0;
    });
    // const listOfCurrentPageData = this.listOfCurrentPageData.filter(item => item.lineState === 0);
    this.checked = listOfCurrentPageData.every(item => this.setOfCheckedId.has(item.whGoodsId));
    this.indeterminate = listOfCurrentPageData.some(item => this.setOfCheckedId.has(item.whGoodsId)) && !this.checked;
  }

  constructor(
    private msg: NzMessageService,
    private commonService: CommonService,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private datePipe: DatePipe,
    private storageCommonService: StorageCommonService,
    private storagePurchaseManageService: StoragePurchaseManageService,
    private services: StorageWarehousOrderService
  ) {
    activatedRoute.queryParams.subscribe((res: any) => {
      this.routeParams = res || {};
      this.formParams.purchaseNumber = this.routeParams.purchaseNumber;
    })
  }

  async ngOnInit() {
    await this.loadPurchaseList();
    await this.loadSupplierList();
    this.loadWarehouseList();

    this.purchaseChange(this.routeParams.purchaseNumber);

    if (this.routeParams.id) {
      this.loadDetailsData();
    }
  }

  // 查询供应商
  async loadSupplierList() {
    const res: any = await this.commonService.getSupplierList();
    // 状态为正常de
    this.supplierOptions = res.filter((item: any) => item.state === 1);
    // this.setSearchOption(res, 'type');
  }

  // 查询仓库
  async loadWarehouseList() {
    let params = {
      page: 1,
      pageSize: 9999
    }
    const {code, data, message}: any = await this.storageCommonService.getWarehouseList(params);
    if (code === 0) {
      this.warehouseOptions = data?.records.filter((item: any) => [1].includes(item.state));
    } else {
      this.msg.error(message);
    }
  }

  // 查询采购单号(状态进行中)
  async loadPurchaseList() {
    let params = {
      state: '2',
      page: 1,
      pageSize: 9999
    }
    const {code, data, message}: any = await this.storagePurchaseManageService.getPurchaseList(params);
    if (code === 0) {
      this.purchaseOptions = data?.records || [];
    } else {
      this.msg.error(message);
    }
  }

  // 详情Details
  async loadDetailsData() {
    let params = {
      id: this.routeParams.id
    }
    const msgId = this.msg.loading('数据加载中..', { nzDuration: 0 }).messageId;
    const {code, data, message}: any = await this.services.getWarehousingDetails(params);
    this.msg.remove(msgId);
    
    if (code === 0) {
      const { list, warehousing } = data || {};
      
      this.detailsData = warehousing || {};
      for (let key in this.formParams) {
        this.formParams[key] = !this.commonService.isEmpty(warehousing[key]) ? warehousing[key] : '';
      }

      list.map((item: any) => item.oldNumber = item.number);
      this.detailedTableData = list || [];
    } else {
      this.msg.error(message);
    }
  }

  /**
   * 选择更多商品
   * ----------------------------------------------------------------
   */
  // 根据采购单ID查询商品list(采购详情)
  async loadGoodTable() {
    let tmpObj = this.purchaseOptions.find(item => item.purchaseNumber === this.formParams.purchaseNumber);
    let params = {
      id: tmpObj.id
    }
    this.goodTableParams.loading = true;
    const {code, data, message}: any = await this.storagePurchaseManageService.getPurchaseDetailData(params);
    this.goodTableParams.loading = false;

    if (code === 0) {
      const {purchase, list} = data || {};

      list.sort((a: any, b: any) => { return a.lineState - b.lineState; });
      this.goodTableParams.tableData = list || [];
    } else {
      this.msg.error(message);
    }
  }

  showMoreGoodsModal() {
    let arr = this.detailedTableData.map(m => m.whGoodsId);
    this.setOfCheckedId = new Set(arr);
    this.setOfCheckedArr = JSON.parse(JSON.stringify(this.detailedTableData));
    
    this.loadGoodTable();
    this.isGoodVisible = true;
  }

  // 关联已选
  relationSelected() {
    if (!this.setOfCheckedId.size) {
      this.msg.warning('请先选择所需关联项!');
      return
    }
    // return
    this.detailedTableData = JSON.parse(JSON.stringify(this.setOfCheckedArr));
    this.isGoodVisible = false;
  }

  /**
   * submit
   * ----------------------------------------------------------------
   */
  verifData() {
    let isNotFilled = this.detailedTableData.some(m => this.commonService.isEmpty(m.number));

    if (this.commonService.isEmpty(this.formParams.purchaseNumber)) {
      this.msg.warning('请选择采购单号');
      return false;
    } else if (this.commonService.isEmpty(this.formParams.whPutId)) {
      this.msg.warning('请选择入库仓库');
      return false;
    } else if (this.commonService.isEmpty(this.formParams.quality)) {
      this.msg.warning('请选择入库品质');
      return false;
    } else if (!this.detailedTableData.length) {
      this.msg.warning('请添加入库明细');
      return false;
    } else if (isNotFilled) {
      this.msg.warning('入库明细中预计入库数量存在未填写项');
      return false;
    } else {
      return true;
    }
  }

  async submitData() {
    if (!this.verifData()) {
      return
    }
    // 采购单信息
    let purchaseObj = this.purchaseOptions.find(item => item.purchaseNumber === this.formParams.purchaseNumber);

    let arrs = this.detailedTableData.map(m => {
      return {
        planDetailsId: m.planDetailsId,
        purchaseId: purchaseObj.id, // 采购单ID
        whGoodsId: m.whGoodsId, // 商品ID
        number: m.number, // 入库数量
        price: m.price, // 入库单价
        purchaseNumber: m.purchaseNumber || 0, // 采购数量
        frozenNumber: m.frozenNumber || 0, // 冻结数量
        stockNumber: m.stockNumber || 0, // 已入库数量
        state: (this.routeParams.id && !this.commonService.isEmpty(m.lineState)) ? m.lineState : 0, // 状态 0正常(新增默认) 1已作废
        type: m.type,  // 商品列表type为分类 (注:编辑时使用返回type即可、新增时根据原商品列表中snState设置type，snState:0对应1、1对应3) // type: 0 指定SN 1SN管控 2多库位 3普通(新增默认)
        closeRemark: !this.commonService.isEmpty(m.closeRemark) ? m.closeRemark : '', // 关闭备注
        actualStorageNumber: !this.commonService.isEmpty(m.actualStorageNumber) ? m.actualStorageNumber : '', // 实际入库数量
        itemSns: !this.commonService.isEmpty(m.itemSns) ? m.itemSns : '', // 商品SN号列表
        libraryText: !this.commonService.isEmpty(m.libraryText) ? m.libraryText : '', // 库位信息
        libraryId: !this.commonService.isEmpty(m.libraryId) ? m.libraryId : '' // 库位id
      }
    })
    let params: any = {
      warehousing: {
        type: 1, // 入库类型(1、采购入库 2、售后入库  3、代售入库 4、借机归还)
        ...this.formParams
      },
      list: arrs
    }
    if (this.routeParams.id) {
      params.warehousing.id = this.routeParams.id;
    }
    // return

    this.submitLoading = true;
    const {code, message}: any = await this.services.editWarehousOrderData(params, this.routeParams.id ? 1 : 0);
    this.submitLoading = false;
    if (code === 0) {
      this.msg.success('操作成功');
      this.pageBack();
    } else {
      this.msg.error(message);
    }
  }

  /**
   * other
   * ----------------------------------------------------------------
   */

  // 入库数量 \ 单价合计
  calcSumTotal(key: string) {
    let sum = 0;
    sum = this.detailedTableData.reduce((total: number, item: any) => {
      return (total || 0) + (item[key] || 0);
    }, 0);

    return isNaN(sum) ? 0 : sum;
  }

  // 行小计
  calcProduct(num: number, price: number) {
    let pTotal = 0;
    pTotal = num * (price ? (Number(price)) : 0);

    return isNaN(pTotal) ? 0 : pTotal;
  }

  // 小计合计
  calcProductTotal() {
    let sum = 0;
    sum = this.detailedTableData.reduce((total: number, item: any) => {
      return (total || 0) + ((item.number || 0) * (item.price || 0));
    }, 0);

    return isNaN(sum) ? 0 : sum;
  }

  // 采购单 Change
  async purchaseChange(value: any) {
    let tmpObj = this.purchaseOptions.find(item => item.purchaseNumber === value);

    this.supplierName = value ? this.filterText(this.supplierOptions, tmpObj?.supId, 'id') : '-';
    this.formParams.supId = value ? tmpObj?.supId : '';
    this.detailedTableData = [];
  }

  // Filter Text
  filterText(arrs: Array<any>, keyVal: any, idKey: string) {
    let tempObjs: any = {};
    if (arrs.length) {
      tempObjs = arrs.find(item => item[idKey] == keyVal);
    }

    return tempObjs?.name || '-';
  }

  // 删除已选商品
  deleteItem(item: any) {
    this.detailedTableData = this.detailedTableData.filter(ele => ele.whGoodsId !== item.whGoodsId);
  }

  pageBack() {
    this.router.navigate(['/storage-center/storage-warehous-list']);
    // history.back();
  }

  // timechange
  timeChange(val: any) {
    this.formParams.arrivalTime = val ? this.datePipe.transform(val, 'yyyy-MM-dd') : '';
  }

  /**
   * 入库明细设置最大值
   * 新建时候的最大值 = 采购数量 - 冻结数量 - 已入库数量
   * 编辑时候的最大值 = 采购数量 - 冻结数量 - 已入库数量 + 该行之前已经填写过的数量
   */
  setMxNumer(item: any) {
    let maxNum = 0; 

    if (this.commonService.isEmpty(this.routeParams.id) || this.routeParams.type == '0') {
      maxNum = (item.purchaseNumber || 0) - (item.frozenNumber || 0) - (item.stockNumber || 0);
    } else {
      maxNum = (item.purchaseNumber || 0) - (item.frozenNumber || 0) - (item.stockNumber || 0) + (item.oldNumber || 0);
    }
    // maxNum = (item.purchaseNumber || 0) - (item.frozenNumber || 0) - (item.stockNumber || 0);

    return maxNum;
  }

  /**
   * Modal 商品禁选
   * 行状态作废 | (采购数量 - 冻结数量 - 已入库数量) = 0
   * @param item 
   * @returns 
   */
  setGoodDisabled(item: any) {
    let cnum = (item.purchaseNumber || 0) - (item.frozenNumber || 0) - (item.stockNumber || 0);
    return item.lineState === 1 || cnum === 0;
    // return item.lineState === 1;
  }
}
